var routes      = exports;
var db          = require("../database");
var eyes        = require("eyes");
var _           = require("../lib/underscore.js");
var util        = require("util");
var crypto      = require('crypto');
var mail        = require('.././mail.js');
var Mongolian = require("mongolian");

var quarterMonths = [
    ["Januar","Februar","Mars"],
    ["April", "Mai", "Juni"],
    ["Juli", "August", "September"],
    ["Oktober", "November", "Desember"]
];

//-------------------------------------------------------------------------
// Primary Views. These are full pages that loads with layout:true.
//-------------------------------------------------------------------------
routes.index = function(req, res) {
    if (req.session.username) {
        res.render('index', {
            title: "Midgard",
            name:   req.session.firstname + " " + req.session.lastname,
            level:  req.session.level,
            userid: req.session.userId,
            navs: {
                summary:    {title:"Startside",lvl:0},
                ideas:      {title:"Idé",lvl:1,phase:'idea'},
                proposals:  {title:"Tilbud",lvl:1,phase:'proposal'},
                tasks:      {title:"Oppdrag",lvl:1,phase:'task'},
                evaluations:{title:"Evaluering",lvl:1,phase:'complete(d?)'},//yes TODO (nix):fix to completed
                settings:   {title:"Innstillinger",lvl:0},
                admin:      {title:"Administrator",lvl:9}
            }

        });
    } else {
        res.redirect("/login");
    }
};
//-------------------------------------------------------------------------
routes.login = function(req,res){
    if (!req.session.username) {
        res.render('login', {title:"Login"});
    } else {
        res.redirect("/");
    }
}
//-------------------------------------------------------------------------
routes.loginDo = function(req,res){
    if (!req.session.username){
        var data = req.body;
        db.getUser(data, function(err, user) {
            sessions.push(req.session);
            if(user) {
                req.session.user        = user;
                req.session.username    = user.username;
                req.session.userId      = user._id.toString();
                req.session.password    = user.password;
                req.session.firstname   = user.firstname;
                req.session.lastname    = user.lastname;
                req.session.level       = user.level;
                req.session.email       = user.email;
                res.redirect("/");
            } else {
                res.redirect("/login");
            }
        });
    } else {
        res.redirect("/login");
    }
}
routes.loginDo.method = 'post';
routes.loginDo.url = '/login/do';
//-------------------------------------------------------------------------
routes.logout = function(req,res){
    if (req.session.username) {
        req.session.destroy();
    }
    res.redirect("/login");
}

//-------------------------------------------------------------------------
// Sub Views: Stuff to be loaded into the #content element in main view.
//-------------------------------------------------------------------------
routes.tasks = function(req,res) {
    var quarter = req.param("quarter", 0);
    var year = new Date().getFullYear() //Gets current year
    if (req.session.username){
        res.render('tasks', {
            layout: false,
            quarter: quarterMonths[quarter],
            year:year
        });
    } else {
        res.redirect("/login");
    }
};
//-------------------------------------------------------------------------
routes.settings = function(req,res) {
    if (req.session.username){
        res.render('settings', {
            layout: false,
            username: req.session.username,
            name: req.session.firstname + " " + req.session.lastname,
            email:req.session.email

        });
    } else {
        res.redirect("/login");
    }
};
//-------------------------------------------------------------------------
var NAMES = {idea: 'idé', task: 'oppdrag', proposal: 'tilbud'};
routes.createModal = function(req,res) {
    // var id = req.query._id;
    var phase = req.query.phase || 'idea';
    var renderParams = {
        layout: false,
        phase: phase,
        NAMES: NAMES
    };
    eyes.inspect(renderParams, "renderParams")
    
    res.render('createModal', renderParams);
}
//-------------------------------------------------------------------------
var RISK_NAMES = {low: "Lav", medium: "Middels", high: "Høy"}
var RISK_BTN_CLASSES = {low: "btn-success", medium: "btn-warning", high: "btn-danger"};
routes.projectView = function(req,res) {
    var id = req.query._id;
    db.getProject(id, function(project) {
        // if(!project) return console.error("project not found");
        // var dateCreated = new Date(project.dateCreated*1000);
        // var dateEnd = new Date(project.dateEnd*1000);
        var f = function(e) {
            if (e) {
                return new Date(e*1000);
            } else {
                return null;
            }
        };
        var renderParams = {
            layout:         false,
            id:             project._id.toString(),
            title:          project.title,
            phase:          project.phase,
            //status:         project.status,     <-- This is a buggy sinner
            budget:         project.budget || '',
            leader:         project.leader   || {id: 'UNCURRENT', name: ''},
            internId:       project.internId || null,
            creator:        project.creator  || 'Trond Giske',
            desc:           project.desc,
            customer:       project.customer || null,
            riskMsg:        project.riskMsg || '',
            riskLabel:      project.phase=='task'?'Risiko':'Status',
            showRiskMsg:    project.phase=='task',
            resources:      project.resources || [],
            risk:           project.risk,
            RISK_NAMES:     project.phase == 'task' ? RISK_NAMES : {low:'Godtatt', medium:'Sent', high: 'Avslag'},
            RISK_BTN_CLASSES: RISK_BTN_CLASSES,
            dateCreated:    dateToString(f(project.dateCreated)),
            dateStart:      dateToString(f(project.dateStart)),
            dateEnd:        dateToString(f(project.dateEnd)),
            NAMES:           NAMES
        };
        eyes.inspect(renderParams, "renderParams")
        
        res.render('projectView', renderParams);
    });
}
//-------------------------------------------------------------------------
routes.ideaView = function(req,res) {
    var id = req.query._id;
    db.getProject(id, function(project) {
        if(!project) return console.error("project not found");
        var dateCreated = new Date(project.dateCreated*1000);
        var renderParams = {
            layout:           false,
            id:               project._id.toString(),
            title:            project.title,
            phase:            project.phase,
            internId:         project.internId || null,
            creator:          project.creator  || {id:'65d40sf', name:'Lars Error'},
            desc:             project.desc,
            canEdit:          (project.creator || {id:'error'}).id == req.session.userId,
            RISK_NAMES:       RISK_NAMES,
            RISK_BTN_CLASSES: RISK_BTN_CLASSES,
            dateCreated:      dateToString(dateCreated) || dateToString(Date.now()),
            NAMES:            NAMES
        };
        eyes.inspect(renderParams, "renderParams")
        
        res.render('ideaView', renderParams);
    });
}
//-------------------------------------------------------------------------
// !! Deprecated !!
// 
// ProjectView will take over 
//
routes.taskView = function(req,res){}
//-------------------------------------------------------------------------
routes.gannt = function(req,res) {}
//-------------------------------------------------------------------------
routes.ideas = function(req,res) {
    db.getIdeas(null, function(ideas) {
        res.render('ideas', {
            layout: false,
            ideas: ideas
        });
    });
};

routes.proposals = function(req,res) {
    var quarter = req.param("quarter", 0);
    var year = new Date().getFullYear() //Gets current year

    if (req.session.username){
        res.render('proposals', {
            layout:false,
            quarter: quarterMonths,
            year: year
        });
    } else {
        res.redirect("/login");
    }
};

routes.evaluations = function(req,res) {
    if (req.session.username){
        res.render('evaluations', {
            layout: false
        });
    } else {
        res.redirect("/login");
    }
};

routes.newuser = function(req,res) {
        res.render('newuser', {
            layout: false
        });
};


routes.summary = function(req,res) {
    if (req.session.username){
        var userId = req.session.userId;
        db.getEvents(userId, function(summaries) {
            res.render('summary', {
                layout: false,
                summaries:summaries
            });
        });
    } else {
        res.redirect("/login");
    }
};

routes.getEvaluation = function(req,res) {
    var sortAttr = {};
    var field     = req.body.sortname;
    var sortOrder = (req.body.sortorder == 'asc' ? 1 : -1);
    var state = req.body.state;
    sortAttr[field] = sortOrder;

    db.projects.find({phase: state}).sort(sortAttr).toArray(function (err, data) {
        var total = 0;
        var page = 1;
        var rows = [];
        var leadername = null;
        if(data){
            for(var i=0;i<data.length;i++){
                if(data[i].leader != undefined && data[i].leader.toString().length >= 24){
                    var leader = data[i].leader;
                    //console.log(leader);
                    //db.getUserById(leader,function(err,user){ <--- Lookup leaderID, set leadername
                }
                var dateCreated = dateToString(new Date(data[i].dateCreated * 1000));
                var dateEnd     = dateToString(new Date(data[i].dateEnd * 1000));
                var evaluated   = (data[i].evaluated == "true" ? "Ja":"Nei");
                data[i].id = data[i]._id.toString();
                data[i].cell = [total,data[i]._id.toString(),data[i].title,data[i].desc,evaluated,leadername||"Ola Nordmann",parseInt(data[i].ecoframe||0),dateCreated,dateEnd];
                rows.push(data[i]);
                total++;
            }
        }
        var result = {
            page:page,
            total:total,
            rows:rows
        }
        res.send(result);
    });
};


routes.getNewGantt= function(req,res) {
    var array = [];
    db.projects.find({phase: 'task'}).toArray(function (err, data) {
        if(err) throw err;
        for(var i=0;i<data.length;i++){
            var state;
            switch(data[i].risk){
                case "low":
                    state = "ganttRed";
                    break;
                case "medium":
                    state = "ganttOrange";
                    break;
                case "low":
                    state = "ganttGreen";
                    break;
                default:
                    state = "ganttGreen";
            }
            var project = {
                name: data[i].title,
                desc: data[i].desc,
                values: [
                    {
                        from:   datstr(data[i].dateCreated || 0),
                        to:     datstr(data[i].dateEnd || 0),
                        desc:   data[i].desc,
                        label:  data[i].desc,
                        customClass: state
                    }
                ]
            };
            array.push(project);
        }
        res.send(array);
    });
}
routes.getGantt= function(req,res) {
    var array = [];
    db.projects.find({phase: 'task'}).sort({dateStart:1}).toArray(function (err, data) {
        if(err) throw err;
        else{
            for(var n = 0;n<data.length;n++){
                var projectId = data[n]._id;
                data[n]._id = projectId.toString()||0;
            }
            res.send(data);
        }

    });
}

routes.getProjectSpreadSheet = function(req,res) {
    var sortAttr = {};
    var field     = req.body.sortname;
    var sortOrder = (req.body.sortorder == 'asc' ? 1 : -1);
    var state = req.body.state;
    sortAttr[field] = sortOrder;
    db.projects.find({phase: state}).sort(sortAttr).toArray(function (err, data) {
        var total = 0;
        var page = 1;
        var rows = [];
        for(var i=0;i<data.length;i++){
            var dateCreated = dateToString(new Date(data[i].dateCreated * 1000));
            var dateEnd = dateToString(new Date(parseInt(data[i].dateEnd) * 1000));
            var leader;
            if(data[i].leader && data[i].leader.name ){leader=data[i].leader.name;}
            else leader="Niklas Humlen";
            data[i].id = data[i]._id.toString();
            data[i].cell = [total,data[i]._id.toString(),data[i].title,data[i].desc,leader,parseInt(data[i].ecoframe||0),dateCreated,dateEnd];
            rows.push(data[i]);
            total++;
        }
        var result = {
            page:page,
            total:total,
            rows:rows
        }
        res.send(result);
    })
};
routes.getProposalSpreadSheet = function(req,res) {
    var sortAttr = {};
    var field     = req.body.sortname;
    var sortOrder = (req.body.sortorder == 'asc' ? 1 : -1);
    var state = req.body.state;
    sortAttr[field] = sortOrder;
    db.projects.find({phase: state}).sort(sortAttr).toArray(function (err, data) {
        var total = 0;
        var page = 1;
        var rows = [];
        for(var i=0;i<data.length;i++){
            var dateCreated = dateToString(new Date(data[i].dateCreated * 1000));
            var dateStart = dateToString(new Date(data[i].dateStart * 1000));
            var dateEnd = dateToString(new Date(parseInt(data[i].dateEnd) * 1000));
            var leader;
            if(data[i].leader && data[i].leader.name ){leader=data[i].leader.name;}
            else leader="Niklas Humlen";
            data[i].id = data[i]._id.toString();
            data[i].cell = [total,data[i]._id.toString(),data[i].title,data[i].desc,leader,
                parseInt(data[i].ecoframe||0),dateCreated,dateStart,dateEnd];
            rows.push(data[i]);
            total++;
        }
        var result = {
            page:page,
            total:total,
            rows:rows
        }
        res.send(result);
    })
};

routes.admin = function(req,res) {
    var level = req.session.level;
    if (req.session.username && level == 9){
        db.getUsers({level:0}, function(userList) {
            res.render('admin', {
                layout: false,
                users: userList,
                garbage: []
            });
        });
    } else {
        res.redirect("/login");
    }
};


routes.updateUser = function(req,res) {
    if (req.session.username){
        var sendMail = false, newMail = false;
        if(req.body._id == "none") { req.body._id = req.session.userId };
        if(req.body.password) { req.body.password = toMD5(req.body.password) };
        if(req.body.email){ sendMail = req.body.email; delete req.body.email; };
        if(req.body.newmail){ newMail = req.body.newmail; req.body.email = newMail; delete req.body.newmail; };
        db.editUser(req.body, function(result) {
                if(sendMail != false){
                    mail.sendMail(sendMail,"Godkjennelse av din bruker på Midgard","Du er blitt godkjent av " +
                        req.session.firstname+" "+req.session.lastname + ", "+
                        "og har nå tilgang til all informasjon på nettsiden.");
                }
                if(newMail != false){
                    req.session.email = newMail;
                }
                res.send(result);
      }
    );
    } else {
        res.redirect("/login");
    }
};

routes.checkUserPass = function(req,res){
    if (req.session.username){
        var pass = toMD5(req.body.password);
        if(pass == req.session.password) {
            res.send("true");
        }
        else {
            res.send("false");
        }
    }
    else {
        res.redirect("/login");
    }
};
routes.setEvaluated = function(req,res) {
    var data = req.body;
    if (req.session.username){
        var _id = data._id;
        delete data._id;
        //eyes.inspect(data);
        db.projects.update({ _id:new Mongolian.ObjectId(_id) }, {$set: data },
            function (err, success) {
                if (err) {
                    throw err;
                    res.send(false);
                }
                res.send(true);
            }
        );
    } else {
        res.redirect("/login");
    }
};


//-------------------------------------------------------------------------
// Minor content boxes.
//-------------------------------------------------------------------------
routes.newIdea = function(req, res){
    if (req.session.username){
        res.render('newidea', {title:"New Idea"});
    } else {
        res.redirect("/login");
    }
};

//-------------------------------------------------------------------------
// Utilities. Stuff like saving cookie or change css & stuff++.
//-------------------------------------------------------------------------
routes.saveCookie = function(req,res) {
    var data = req.body;
    res.cookie('theme', data['themechanger'], { maxAge: 15552000000 });
    req.session.themeLoaded = true;
    res.redirect('back');
    console.log("Theme changed:" + data['themechanger']);
};
routes.saveCookie.method = 'post';
routes.getEvaluation.method = 'post';
routes.getProjectSpreadSheet.method = 'post';
routes.getProposalSpreadSheet.method = 'post';
routes.updateUser.method = 'post';
routes.checkUserPass.method = 'post';
routes.getGantt.method = 'post';
routes.getNewGantt.method = 'post';
routes.setEvaluated.method = 'post';



//-------------------------------------------------------------------------

function dateToString(aDate){
    if(!aDate) return null;
    var dateString = aDate.getDate() + "."+(aDate.getMonth()+1) + "."+aDate.getFullYear();
    return dateString;
}

function stringToDate(strDate) {
    var parts = strDate.split('.');
    var dd = parts[0];
    var mm = parts[1];
    var yy = parts[2];
    var americanFormat = mm+'/'+dd+'/'+yy
    eyes.inspect(americanFormat, "American Format")
    return parseInt(Date.parse(americanFormat)/1000);
}

function toMD5(data){
    var md5  = crypto.createHash('md5').update(data).digest("hex");
    return md5;
}
function datstr(fdate) {
    return "/Date("+  Math.floor(fdate*1000) +")/";
}